<template>
	<view class="personal-data">
		<view class="wrapper">
			<view class="wrapList">
				<view class="item acea-row row-between-wrapper on">
					<view class="picTxt acea-row row-between-wrapper">
						<view class="pictrue">
							<div class="pictrue">
								<!-- #ifdef MP-WEIXIN -->
								<button class="pictrue_btn" open-type="chooseAvatar" @chooseavatar="getChooseavatar">
									<img :src="avatar" />
								</button>
								<!--  #endif -->
								<!-- #ifdef APP-PLUS-->
								<button class="pictrue_btn" @click="changeAvatar">
									<img :src="avatar" />
								</button>
								<!--  #endif -->
							</div>
						</view>
						<view class="text">
							<view class="name line1">
								<u--input placeholder="请输入昵称" border="surround" @change="submit" type="nickname"
									v-model="nickname" suffixIcon="edit-pen"></u--input>
							</view>
							<view class="phone" v-if="userInfo.phone">
								绑定手机号：
								<text>{{ userInfo.phone }}</text>
							</view>
							<!---->
							<view class="phone" v-if="!userInfo.phone">
								<button class="binding" open-type="getPhoneNumber" @getphonenumber="btns">
									<text>获取手机号</text>
								</button>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
		<view class="list">
			<u-cell-group>
				<u-cell title="用户协议" :isLink="true" @click="goAgreement(`USER_AGREEMENT`)"></u-cell>
				<u-cell title="隐私协议" :isLink="true" @click="goAgreement(`PRIVACY_POLICY`)"></u-cell>
				<u-cell title="账号注销" :isLink="true" @click="accountCancellation"></u-cell>
			</u-cell-group>
		</view>
		<!-- <view class="modifyBnt bg-color-red" @click="submit">保存修改</view> -->
		<view class="logOut cart-color acea-row row-center-wrapper" @click="logout">退出登录</view>

	</view>
</template>
<script>
	import {
		mapGetters
	} from "vuex";
	import {
		trim,
		isWeixin
		// ,
		// chooseImage
	} from "@/utils";
	import {
		VUE_APP_API_URL
	} from "@/config";
	import {
		postUserEdit,
		getLogout,
		switchH5Login,
		getUserInfo,
	} from "@/api/user";
	import cookie from "@/utils/store/cookie";
	import store from "@//store";
	import dayjs from "dayjs";
	import {
		customUpdateAvatar
	} from "@/utils/customUpdateAvatar"
	import {
		bindingPhone
	} from "@/api/user";
	export default {
		name: "PersonalData",
		components: {
			// VueCoreImageUpload
		},
		data: function() {
			return {
				nickname: '',
				avatar: "",
				isWeixin: false,
				currentAccounts: 0,
				switchUserInfo: [],
				userIndex: 0,
			}
		},

		computed: {
			...mapGetters(["userInfo"])
		},
		mounted: function() {
			this.avatar = this.userInfo.avatar;
			this.nickname = this.userInfo.nickname;
			this.isWeixin = isWeixin();
			this.getUserInfo();
		},

		methods: {
			accountCancellation() {
				uni.showModal({
					title: '提示',
					content: '是否确认账号注销操作？',
					success(res) {
						if (res.confirm) {
							uni.showToast({
								title: '申请中...',
								icon: 'none',
								duration: 2000
							});
						}
					}
				})
			},
			changeAvatar() {
				let that = this
				uni.chooseImage({
					count: 1, //默认9
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album'], //从相册选择
					success: function(res) {
						console.log(res.tempFilePaths[0]);

						that.getQinNiuYun(res.tempFilePaths[0])

					}
				});
			},
			async getQinNiuYun(url) {
				const result = await customUpdateAvatar(url)
				console.log(result)
				this.avatar = result
				this.submit()
			},
			// bindblur(e) {
			// 	console.log(e)
			// 	this.nickName = e
			// 	this.submit()

			// },
			btns(e) {
				console.log(e, 'e.detail.code换取手机号')
				if (e.detail.errMsg == 'getPhoneNumber:fail user deny') return
				let thit = this;
				// 判断一下这里是不是小程序 如果是小程序，走获取微信手机号进行绑定
				if (e.mp.detail.errMsg == "getPhoneNumber:ok") {
					uni.showLoading({
						title: "绑定中"
					});
					bindingPhone({
							encryptedData: e.mp.detail.encryptedData,
							iv: e.mp.detail.iv
						})
						.then(res => {
							// this.User();
							thit.$store.dispatch("userInfo", true);
							uni.hideLoading();
							uni.showToast({
								title: res.msg,
								icon: "success",
								duration: 2000
							});
						})
						.catch(error => {
							uni.hideLoading();
							thit.$store.dispatch("userInfo", true);
							console.log(error);
							uni.showToast({
								title: error.msg ||
									error.response.data.msg ||
									error.response.data.message,
								icon: "none",
								duration: 2000
							});
						});
				} else {
					uni.showToast({
						title: "已拒绝授权",
						icon: "none",
						duration: 2000
					});
				}

				console.log(e)

			},



			base64(url, type) {
				return new Promise((resolve, reject) => {
					uni.getFileSystemManager().readFile({
						filePath: url, //选择图片返回的相对路径
						encoding: 'base64', //编码格式
						success: res => {
							resolve('data:image/' + type.toLocaleLowerCase() + ';base64,' + res.data)
							// resolve(res.data)
						},
						fail: res => reject(res.errMsg)
					})
				})
			},
			goAgreement(type) {
				this.$yrouter.push({
					path: `/userPack/pages/user/agreement/index`,
					query: {
						type
					}
				});
			},
			async getChooseavatar(e) {
				console.log(e)
				// this.base64(e.detail.avatarUrl, "png").then(res => {
				// 	this.avatar = res;
				// 	console.log(this.avatar)
				// })
				const result = await customUpdateAvatar(e.detail.avatarUrl)
				console.log(result)
				this.avatar = result
				this.submit()
			},
			goChangePassword() {
				this.$yrouter.push("/pages/user/ChangePassword/index");
			},
			switchAccounts: function(index) {
				let that = this;
				this.userIndex = index;
				let userInfo = this.switchUserInfo[this.userIndex];
				if (this.switchUserInfo.length <= 1) return true;
				if (userInfo === undefined) {
					uni.showToast({
						title: "切换的账号不存在",
						icon: "none",
						duration: 2000,
					});
					return;
				}
				if (userInfo.user_type === "h5") {
					switchH5Login()
						.then(({
							data
						}) => {
							uni.hideLoading();
							const expires_time = dayjs(data.expires_time);
							store.commit("login", data.token, expires_time);
							that.$emit("changeswitch", false);
							location.reload();
						})
						.catch((err) => {
							uni.hideLoading();
							uni.showToast({
								title: err.msg || err.response.data.msg || err.response.data.message,
								icon: "none",
								duration: 2000,
							});
						});
				} else {
					cookie.set("loginType", "wechat", 60);
					uni.hideLoading();
					this.$store.commit("logout");
					this.$emit("changeswitch", false);
				}
			},
			getUserInfo: function() {
				let that = this;
				getUserInfo().then((res) => {});
			},
			submit: function() {
				postUserEdit({
					nickname: trim(this.nickname),
					avatar: this.avatar,
				}).then(
					(res) => {
						this.$store.dispatch("userInfo", true);
					},
					(err) => {
						uni.showToast({
							title: err.msg || err.response.data.msg || err.response.data.message,
							icon: "none",
							duration: 2000,
						});
					}
				);
			},
			logout: function() {
				uni.showModal({
					title: "提示",
					content: "确认退出登录?",
					success: (res) => {
						if (res.confirm) {
							getLogout().then((res) => {
								this.$store.commit("logout");
								if (this.$deviceType == 'routine' || this.$deviceType == 'app') {
									this.$yrouter.reLaunch({
										path: "/pages/launch/index",
										query: {
											type: 'User'
										},
									});
								}
								if (this.$deviceType == 'weixinh5' || this.$deviceType ==
									'weixin') {
									this.$yrouter.replace({
										path: "/userPack/pages/user/Login/index",
										query: {},
									});
								}
							}).catch((err) => {});

						} else if (res.cancel) {
							// console.log("用户点击取消");
						}
					},
				});
			},
		},
	};
</script>
<style>
	.pictrue_btn {
		width: 48px;
		height: 46px;
		padding: 0;
	}

	.binding {
		width: 180rpx;
		margin-top: 0.1 * 100rpx;
		display: inline-block;
		padding: 5rpx 10rpx;
		background-color: #ca1f10;
		border-radius: 50px;
		font-size: 12px;
		line-height: 1.5;
		border: 1px solid #e8695e;
		color: #ffffff;
	}
</style>